<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Drag and Drop Example</title>
    <style>
        .container {
            width: 300px;
            margin: 10px;
            padding: 10px;
            border: 1px solid #ccc;
            float: left;
        }

        .item {
            margin: 5px;
            padding: 5px;
            border: 1px solid #000;
            background-color: #f9f9f9;
            cursor: move;
        }
    </style>
</head>

<body>

    <div class="container" id="container1">
        <div class="item" draggable="true" id="item1">Item 1</div>
        <div class="item" draggable="true" id="item2">Item 2</div>
    </div>

    <div class="container" id="container2">
        <div class="item" draggable="true" id="item3">Item 3</div>
        <div class="item" draggable="true" id="item4">Item 4</div>
    </div>
    <div class="container" id="container2">

    </div>

    <script>
        // 添加拖拽事件监听器到所有可拖拽的元素
        var dragItems = document.querySelectorAll('.item');
        var containerItems = document.querySelectorAll('.container');
        dragItems.forEach(function (item) {
            item.addEventListener('dragstart', handleDragStart, false);
            item.addEventListener('dragend', handleDragEnd, false);
        });
        containerItems.forEach(function (item) {
            item.addEventListener('dragover', handleDragOver, false);
            item.addEventListener('drop', handleDrop, false);
        });

        // 处理拖拽开始事件
        function handleDragStart(event) {
            this.style.opacity = '0.4'; // 设置拖拽元素的透明度
            event.dataTransfer.effectAllowed = 'move';
            event.dataTransfer.setData('AA', event.target.id);
        }

        // 处理拖拽事件
        function handleDragOver(event) {
            if (event.preventDefault) {
                event.preventDefault(); // 必须调用这个方法，否则拖拽不会生效
            }
            event.dataTransfer.dropEffect = 'move';
            return false;
        }

        // 处理放置事件
        function handleDrop(event) {
            if (event.stopPropagation) {
                event.stopPropagation(); // 防止事件冒泡到可放置元素之外
            }
            var data = event.dataTransfer.getData('AA');
            console.log('event', event)
            event.currentTarget.appendChild(document.querySelector(`#${data}`));
            return false;
        }

        // 处理拖拽结束事件
        function handleDragEnd(event) {
            this.style.opacity = '1'; // 恢复拖拽元素的透明度
        }

        /*
        
            item.addEventListener('dragover', handleDragOver, false);
          item.addEventListener('drop', handleDrop, false);
        */
    </script>

</body>

</html>